package org.amphiprion.descentv2assistant.adapter;

import java.io.File;

import org.amphiprion.descentv2assistant.App;
import org.amphiprion.descentv2assistant.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class PhotoAdapter extends BaseAdapter {
	private final String[] files;
	private final LayoutInflater inflater;
	private final File directory;
	private final boolean empty;
	private final Context context;

	public PhotoAdapter(Context context, File directory) {
		this.inflater = LayoutInflater.from(context);
		this.directory = directory;
		this.context = context;
		files = directory.list();
		empty = !(files != null && files.length > 0);
	}

	@Override
	public int getCount() {
		if (empty) {
			return 1;
		}
		return files.length;
	}

	@Override
	public Object getItem(int index) {
		if (empty) {
			return null;
		}
		return files[index];
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int index, View view, ViewGroup viewGroup) {
		ViewHolder holder = null;
		if (view == null) {
			holder = new ViewHolder();
			view = inflater.inflate(R.layout.item_photo_gallery, null);
			view.setLayoutParams(new Gallery.LayoutParams(App.dpiToPixels(context, 100), App.dpiToPixels(context, 100)));

			holder.img = (ImageView) view;
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		if (empty) {
			holder.img.setImageDrawable(context.getResources().getDrawable(R.drawable.no_photo));
		} else {
			setWithScalledImage(holder.img, directory.getAbsolutePath() + "/" + files[index]);
		}
		return holder.img;
	}

	private void setWithScalledImage(ImageView mImageView, String mCurrentPhotoPath) {
		int targetW = App.dpiToPixels(context, 100); // 200;// mImageView.getWidth();
		int targetH = targetW;// mImageView.getHeight();
		// Get the dimensions of the bitmap
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		int photoW = bmOptions.outWidth;
		int photoH = bmOptions.outHeight;

		// Determine how much to scale down the image
		int scaleFactor = Math.max(1, Math.min(photoW / targetW, photoH / targetH));

		// Decode the image file into a Bitmap sized to fill the View
		bmOptions.inJustDecodeBounds = false;
		bmOptions.inSampleSize = scaleFactor;
		bmOptions.inPurgeable = true;

		Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		mImageView.setImageBitmap(bitmap);
	}

	class ViewHolder {
		ImageView img;
	}
}
